﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _7DaysToDieTools.Class;
using System.Threading;

namespace _7DaysToDieTools
{
    /// <summary>
    /// 下载文件进度条窗口
    /// </summary>
    public partial class FormDown : Form
    {
        private int type = 0;
        private List<string> tmpList = null;
        private string localPath = "";
        /// <summary>
        /// 初始化下载界面
        /// </summary>
        /// <param name="pForm">父窗体</param>
        /// <param name="URLS">下载文件的URL列表</param>
        public FormDown(Form pForm,List<string> URLS)
        {
            InitializeComponent();
            if (pForm == null)
            {
                this.StartPosition = FormStartPosition.CenterScreen;
            }
            else
            {
                this.Location = new Point(pForm.Location.X + pForm.Width / 2 - this.Width / 2, pForm.Location.Y + pForm.Height / 2 - this.Height / 2);
            }
            tmpList = URLS;
            type = 0;
        }

        private void FormDown_Load(object sender, EventArgs e)
        {

        }

        private void FormDown_Shown(object sender, EventArgs e)
        {
            try
            {
                NetAction NA = null;
                if (tmpList == null)
                {
                    this.DialogResult = DialogResult.No;
                    this.Close();
                }
                pbarTotal.Maximum = tmpList.Count;
                foreach (var item in tmpList)
                {
                    labelFileName.Text = Path.GetFileName(item);
                    pbarTotal.Value++;
                    NA = new NetAction();
                    if (type == 0)
                    {
                        NA.DownFile(item, pbarOne);
                    }
                    else if(type == 1)
                    {
                        NA.DownFile(item, localPath, pbarOne);
                    }
                    while (!NA.Comp)
                    {
                        Thread.Sleep(100);
                        this.Refresh();
                        Application.DoEvents();
                    }
                }
                this.DialogResult = DialogResult.Yes;
                NA = null;
                this.Close();
            }
            catch(Exception x)
            {
                MessageBox.Show("下载文件出错！\n" + x.Message);
                this.DialogResult = DialogResult.No;
                this.Close();
            }
        }
    }
}
